﻿using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Nature.Toolkit.GMix.Generic
{
    [Serializable]
    public class GenericExpression : IExpression, ICloneable
    {
        private List<IComponent> m_components = new List<IComponent>();        

        [Serializable]
        class LinkedComponent : GenericComponent
        {
            public LinkedComponent(GenericExpression expression, string componentName, bool isRoot) : base(expression, componentName, isRoot) { }
        }

        public GenericExpression Clone()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, this);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                return (GenericExpression)formatter.Deserialize(ms);
            }
        }


        public GenericComponent CreateComponent(string componentName, bool isRoot = false)
        {
            GenericComponent comp = new LinkedComponent(this, componentName, isRoot);
            m_components.Add(comp);
            return comp;
        }

        public GenericExpression() 
        {
            Units = new UnitsSet() 
            {
                CompositionScale = 1.0, 
                IsMassBased = false, 
                PressureUnits = PressureUnits.Atmosphere, 
                TemperatureUnits =  TemperatureUnits.Kelvin
            };
        }
        public GenericExpression(UnitsSet unitsSet)
        {
            Units = unitsSet;
        }

        public UnitsSet Units { get; private set; }

        #region IExpression Members

        public IEnumerable<IComponent> Components
        {
            get { return m_components; }
        }

        #endregion

        #region ICloneable Members

        object ICloneable.Clone()
        {
            return this.Clone();
        }

        #endregion
    }
}
